from django.shortcuts import render
from learning_logs.models import Topic, Entry
from .forms import TopicForm, EntryForm
from django.http import HttpResponseRedirect, Http404
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required


def index(request):
	return render(request, 'learning_logs/index.html')


@login_required
def topics(request):
	topics = Topic.objects.filter(owner=request.user).order_by('date_added')
	context = {'topics': topics}
	return render(request, 'learning_logs/topics.html', context)


@login_required
def topic(request, topic_id):
	topic = Topic.objects.get(id=topic_id)
	#
	if topic.owner != request.user:
		raise Http404
	entries = topic.entry_set.order_by('-date_added')
	context = {'topic': topic, "entries": entries}
	return render(request, 'learning_logs/topic.html', context)


@login_required
def new_topic(request):
	'''添加新主题'''
	if request.method != 'POST':#不等于POST就是GET
		#空表单
		form = TopicForm
	else:
		'''request为POST的时候的做法'''
		#将提交的数据保存再form上
		form = TopicForm(request.POST)
		#在提交保存数据库前判断数据是否合法
		if form.is_valid():
			#将表格暂时保存在new_topic中，然后将new_topic的owner字段匹配上request的user
			new_topic = form.save(commit=False)
			new_topic.owner = request.user
			new_topic.save()
			#HttpResponseRedirect重定向到topics页面
			#reverse获取topics页面的url(appname+url中的name)
			return HttpResponseRedirect(reverse('learning_logs:topics'))
	'''request为GET的时候的做法'''
	#展示上下文
	context = {'form': form}
	#把request请求的对象返回过去，调用new_topic.html页面，同时加上上下文（数据）context，在模版里面就可以直接使用那些数据
	return render(request, 'learning_logs/new_topic.html', context)


@login_required
def new_entry(request, topic_id):
	topic = Topic.objects.get(id=topic_id)
	if request.method != 'POST':
		form = EntryForm
	else:
		form = EntryForm(data=request.POST)
		if form.is_valid():
			#commit=Flase django创建新的条目对象赋值给new_entry，不直接存进数据库
			new_entry = form.save(commit=False)
			#new_entry.topic----EntryForm.model----models.new_entry.topic与topic关联
			new_entry.topic = topic
			#关联后再保存
			new_entry.save()
			return HttpResponseRedirect(reverse('learning_logs:topic', args=[topic_id]))

	context = {'topic': topic, 'form': form}
	return render(request, 'learning_logs/new_entry.html', context)


@login_required
def edit_entry(request, entry_id):
	entry = Entry.objects.get(id=entry_id)
	topic = entry.topic

	if request.method != 'POST':
		#用当前条目entry填充表单
		form = EntryForm(instance=entry)
	else:
		#当request为post的时候，instance（原来的）， data（修改后的）entry
		form = EntryForm(instance=entry, data=request.POST)
		if form.is_valid():
			form.save()
			return HttpResponseRedirect(reverse('learning_logs:index', args=[topic.id]))

	context = {'entry': entry, 'topic': topic, 'form': form}
	return render(request, 'learning_logs/edit_entry.html', context)


